import storage from '@/utils/storage'
import { ACCESS_TOKEN, IS_BIND_MOBILE } from '@/store/mutation-types'
import * as LoginApi from '@/api/login'
const state = {
	// 登录 access_token
	access_token: '' || storage.get(ACCESS_TOKEN),
	is_bind_mobile: false || storage.get(IS_BIND_MOBILE)
}

const getters = {
	// 判断是否已经登录
    isLogin: state => {
        let retn = false
        if (state.access_token) {
			retn = true
        }
        return retn
    },
	// 是否绑定手机号
	is_bind_mobile: state => state.is_bind_mobile,
	// access_token
	access_token: state => state.access_token
}

const actions = {
    logout({commit}) {
        commit('removeUserData')
    },
	// 微信小程序快捷登录
	mpWxLogin({ commit }, data) {
	  return new Promise((resolve, reject) => {
	    LoginApi.mpWxLogin(data)
	      .then(response => {
			commit('setUserData', response.data)
	        resolve(response)
	      })
	      .catch(reject)
	  })
	}
}

const mutations = {
    setUserData: (state, {access_token, is_bind_mobile}) => {
      state.token = access_token
	  state.is_bind_mobile = is_bind_mobile
	  // 过期时间30天
	  const expiryTime = 30 * 86400
	  // 保存tokne和userId到缓存
	  storage.set(ACCESS_TOKEN, access_token, expiryTime)
	  storage.set(IS_BIND_MOBILE, is_bind_mobile, expiryTime)
    },
	removeUserData(state) {
		storage.remove(ACCESS_TOKEN)
		storage.remove(IS_BIND_MOBILE)
		state.token = ''
		state.is_bind_mobile = false
	}
}

export default {
    namespaced: true,
    state,
    actions,
    getters,
    mutations
}
